{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'channels_last'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import argparse\n",
    "import sys\n",
    "import tensorflow as tf\n",
    "\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "from keras.layers.core import Dense,Flatten\n",
    "from keras.layers.convolutional import Conv2D\n",
    "from keras.layers.pooling import MaxPooling2D\n",
    "from keras.layers import Dropout\n",
    "\n",
    "from keras import backend as K\n",
    "\n",
    "K.image_data_format()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-2-f238acdbd1a2>:2: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /data/train-images-idx3-ubyte.gz\n",
      "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Extracting /data/t10k-images-idx3-ubyte.gz\n",
      "Extracting /data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "data_dir = '/data'\n",
    "mnist = input_data.read_data_sets(data_dir,one_hot=True)\n",
    "\n",
    "x = tf.placeholder(tf.float32,[None,784])\n",
    "y_ = tf.placeholder(tf.float32,[None,10])\n",
    "learning_rate = tf.placeholder(tf.float32)\n",
    "\n",
    "with tf.name_scope('reshape'):\n",
    "    x_image = tf.reshape(x,[-1,28,28,1])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#第一层卷积\n",
    "net = Conv2D(32,kernel_size=[3,3],strides=[1,1],activation='relu',padding='same',input_shape=[28,28,1],kernel_regularizer=tf.keras.regularizers.l2(0.001))(x_image) \n",
    "#原本不考虑不池化，但不理想，还是继续池化\n",
    "net = MaxPooling2D(pool_size=[2,2])(net)\n",
    "#net = Dropout(0.25)(net)\n",
    "#第二层卷积\n",
    "net = Conv2D(64,kernel_size=[5,5],strides=[1,1],activation='relu',padding='same',kernel_regularizer=tf.keras.regularizers.l2(0.01))(net)\n",
    "#第二层池化\n",
    "net = MaxPooling2D(pool_size=[2,2])(net)\n",
    "#net = Dropout(0.25)(net)\n",
    "#第三层卷积，原本以后会更好，发现不行\n",
    "\n",
    "#拉成一维数据,7*7*64\n",
    "net = Flatten()(net)\n",
    "net = Dense(1024,activation='relu',kernel_initializer='random_uniform',bias_initializer='zeros')(net)\n",
    "net = Dropout(0.4)(net)\n",
    "net = Dense(10,activation='softmax',kernel_initializer='random_uniform',bias_initializer='zeros')(net)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "from keras.objectives import categorical_crossentropy\n",
    "cross_entropy = tf.reduce_mean(categorical_crossentropy(y_,net))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "l2_loss = tf.add_n([tf.nn.l2_loss(w) for w in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n",
    "total_loss = cross_entropy + 7e-5*l2_loss\n",
    "\n",
    "train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sess = tf.Session()\n",
    "K.set_session(sess)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step 100, entropy loss: 1.227588, l2_loss: 1366.831421, total loss: 1.323266\n",
      "0.77\n",
      "step 200, entropy loss: 0.305172, l2_loss: 1369.388428, total loss: 0.401029\n",
      "0.93\n",
      "step 300, entropy loss: 0.381546, l2_loss: 1370.169800, total loss: 0.477458\n",
      "0.91\n",
      "step 400, entropy loss: 0.133363, l2_loss: 1370.552856, total loss: 0.229301\n",
      "0.98\n",
      "step 500, entropy loss: 0.250040, l2_loss: 1370.789185, total loss: 0.345995\n",
      "0.94\n",
      "step 600, entropy loss: 0.201631, l2_loss: 1370.946411, total loss: 0.297598\n",
      "0.97\n",
      "step 700, entropy loss: 0.157823, l2_loss: 1371.097168, total loss: 0.253800\n",
      "0.98\n",
      "step 800, entropy loss: 0.085298, l2_loss: 1371.228394, total loss: 0.181284\n",
      "1.0\n",
      "step 900, entropy loss: 0.120363, l2_loss: 1371.313110, total loss: 0.216355\n",
      "0.98\n",
      "step 1000, entropy loss: 0.118402, l2_loss: 1371.388550, total loss: 0.214399\n",
      "0.96\n"
     ]
    }
   ],
   "source": [
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)\n",
    "\n",
    "for step in range(1000):\n",
    "    batch_xs,batch_ys = mnist.train.next_batch(100)\n",
    "    lr = 0.02\n",
    "    _,loss,l2_loss_value,total_loss_values = sess.run([train_step,cross_entropy,l2_loss,total_loss],feed_dict={x:batch_xs,y_:batch_ys,learning_rate:lr})\n",
    "    \n",
    "    if(step+1)%100 == 0:\n",
    "        print('step %d, entropy loss: %f, l2_loss: %f, total loss: %f' % \n",
    "            (step+1, loss, l2_loss_value, total_loss_values))\n",
    "        correct_prediction = tf.equal(tf.argmax(net,1),tf.argmax(y_,1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "        print(sess.run(accuracy,feed_dict={x:batch_xs,y_:batch_ys}))\n",
    "    if(step+1) % 1000 == 0:\n",
    "        print(sess.run(accuracy, feed_dict={x: mnist.test.images,\n",
    "                                    y_: mnist.test.labels}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 本地虚拟机没法运行到3000次，但1000次有到99%"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7rc1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
